<template>
  <div class="split_box">
    <el-dialog
      @close="handleClose(false)"
      @open="handleOpen"
      close-on-press-escape
      v-dialogDrag
      title="拆分编辑"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :visible="showSplit"
      width="750px"
    >
      <div>
        <el-form
          style="padding-right: 15px"
          class="tab_form"
          label-position="right"
          :model="form"
          ref="form"
          size="mini"
          label-width="auto"
        >
          <el-row :gutter="16" type="flex">
            <el-col :span="12">
              <el-form-item label="任务号:" prop="token">
                <el-input disabled v-model="form.token"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班产号:" prop="productionTaskNumber">
                <el-input disabled v-model="form.productionTaskNumber">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="零件号:" prop="partNumber">
                <el-input disabled v-model="form.partNumber"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工序号:" prop="processNumber">
                <el-input disabled v-model="form.processNumber"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来件数量:" prop="partTotalCount">
                <el-input disabled v-model="form.partTotalCount">
                  <template slot="append">个</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="拆分:">
                <el-input-number
                  v-model.number="toolingNumber"
                  @change="handleChange"
                  :min="1"
                  :max="Number(form.toolingNumber)"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-if="isAllToolingNumber">
          <!-- 无法平分配,请手动调整 -->
        </div>
        <el-table border :data="assignData" style="width: 100%">
          <el-table-column
            prop="batchNumber"
            label="批次号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="partTotalCount"
            label="来件数量"
            align="center"
          >
            <template slot-scope="scope">
              <el-input-number
                :style="{
                  border: isAllPartTotalNumber ? '1px solid red' : ''
                }"
                size="small"
                v-model.number="scope.row.partTotalCount"
                :min="1"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            prop="isSetDev"
            label="是否分配"
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isSetDev"
                :active-value="true"
                :inactive-value="false"
                size="small"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="partTotalCount"
            label="分配设备"
            align="center"
          >
            <template slot-scope="scope">
              <el-cascader
                :disabled="!scope.row.isSetDev"
                :props="defaultProps"
                v-model="scope.row.val"
                :options="devList(scope.row.deviceInfoList)"
                size="small"
                @change="cascaderChange"
              ></el-cascader>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="toolingNumber" label="工装数" align="center">
            <template slot-scope="scope">
              <el-input-number
                :style="{
                  border: isAllToolingNumber ? '1px solid red' : '',
                }"
                size="small"
                v-model.number="scope.row.toolingNumber"
                :min="1"
              ></el-input-number>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="a3" label="分配" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.distribution"> </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="设备编号" align="center">
            <template slot-scope="scope">
              <el-cascader
                :disabled="!scope.row.distribution"
                v-model="scope.row.deviceValue"
                :options="deviceOption"
                :props="defaultProps"
                size="small"
              ></el-cascader>
            </template></el-table-column
          > -->
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose(false)">取 消</el-button>
        <el-button
          :loading="btnLoading"
          size="mini"
          type="primary"
          @click="submitForm('form')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// partTotalCount

import { postSplit } from "@/api/combinedFurnace";
import { pad } from "@/utils/index";
export default {
  components: {},
  computed: {
    devList() {
      return function(list) {
        return list.map(item => {
          return {
            ...item,
            deviceName: item.deviceTypeName,
            deviceToken: item.deviceTypeToken
          };
        });
      };
    },
    isAllToolingNumber() {
      return this.allToolingNumber != this.form.toolingNumber;
    },
    isAllPartTotalNumber() {
      return this.allPartTotalNumber != this.form.partTotalCount;
    },
    allToolingNumber() {
      const numbers = this.assignData.map(item => item.toolingNumber);
      var sumValue = numbers.reduce(function(sum, number) {
        //sum2 前两个数的和
        return Number(sum) + Number(number);
      }, 0);
      return sumValue;
    },
    allPartTotalNumber() {
      const numbers = this.assignData.map(item => Number(item.partTotalCount));
      var sumValue = numbers.reduce(function(sum, number) {
        //sum2 前两个数的和
        return Number(sum) + Number(number);
      }, 0);
      return sumValue;
    }
  },
  props: {
    deviceOption: {
      type: Array,
      default: () => []
    },
    showSplit: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      assignData: [],
      form: { toolingNumber: 0, partTotalNumber: 0 },
      tableData: [],
      defaultProps: {
        value: "deviceToken",
        label: "deviceName",
        children: "deviceList"
      },
      toolingNumber: 1,

      btnLoading: false
    };
  },
  mounted() {},
  watch: {},
  methods: {
    cascaderChange(val) {},
    devSet() {
      this.assignData.forEach(item => {
        // isSetDev 是否选中设备
        // if (!item.isSetDev) {
        //   item.deviceInfo = {
        //     deviceName: "",
        //     deviceToken: ""
        //   };
        // }
        if (item.val && item.val.length && item.isSetDev) {
          const token = item.val[item.val.length - 1];
          item.deviceInfoList.forEach(dev => {
            dev.deviceList.forEach(li => {
              if (li.deviceToken == token) {
                item.deviceInfo = li;
              }
            });
          });
        }
      });
    },
    // 生成规则token
    useToken(form, index) {
      return `${this.$moment().format("YYYYMMDD")}-${form.partNumber}-${
        form.batchNumber
      }-${form.processNumber}-2-${pad(index + 1)}`;
    },
    submitForm() {
      // deviceAssignment

      if (this.isAllPartTotalNumber) {
        this.$msg("请调整来件数量拆分!");
        return;
      }
      const parts = this.form;
      // 设备分配
      this.devSet();
      this.btnLoading = true;
      this.assignData = this.assignData.map((item, index) => {
        delete item.id;
        return {
          ...item,
          parentTaskNumber: this.form.token,
          taskNumber: this.useToken(this.form, index),
          token: this.useToken(this.form, index),
          state: "分炉"
        };
      });
      console.log(this.assignData);
      const ass = _.cloneDeep(this.assignData);
      ass.push({
        ...this.form,
        state: "分炉"
      });
      postSplit(ass, this.form.token)
        .then(res => {
          this.$msg({
            message: "拆分成功!",
            type: "success"
          });

          this.handleClose();
          this.$emit("closeAssignDialog", true);
        })
        .finally(f => {
          this.btnLoading = false;
        });
    },
    deviceChange() {},
    handleChange(val) {
      // 偶数 20工装数 7 7 6
      this.assignData = [];
      const partTotalCount = Number(this.form.partTotalCount) / val;
      let saveVal = [];
      if (this.form.deviceInfo.deviceToken) {
        let typeToken = "";
        for (let item of this.form.deviceInfoList) {
          for (let param of item.deviceList) {
            if (param.deviceToken === this.form.deviceInfo.deviceToken) {
              typeToken = item.deviceTypeToken;
            }
          }
        }
        saveVal.push(typeToken, this.form.deviceInfo.deviceToken);
      }
      for (let i = 0; i < val; i++) {
        this.assignData.push({
          ...this.form,
          partTotalCount: Math.floor(partTotalCount),
          val: saveVal,
          isSetDev: false
        });
      }
      console.log(" this.assignData :>> ", this.assignData);
    },
    handleChangeSplit(val) {},
    //弹窗打开执行操作
    handleOpen() {},

    // 弹窗关闭执行操作
    handleClose(isRefresh) {
      this.toolingNumber = 1;
      this.assignData = [];
      this.$emit("update:showSplit", false);
    }
  }
};
</script>

<style lang="scss" scoped>
.tab_form {
  /* margin-right: 15px; */
  /deep/ .el-row--flex {
    flex-wrap: wrap;
  }
}
.unit {
  margin: -28px 0 0 280px;
}
</style>
